package com.wanlian.router.ui.me;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;

import com.wanlian.router.R;
import com.wanlian.router.bean.FeedbackType;

import java.util.List;

/**
 * Created by Hyu on 2018/9/27.
 * Email: fvaryu@163.com
 */
public class FeedbackTypeAdapter extends RecyclerView.Adapter<FeedbackTypeAdapter.H> {

    private List<FeedbackType> mFeedbackTypes;
    private int selectPosition = -1;
    private OnSelectChangedListener mOnSelectChangedListener;

    public void setOnSelectChangedListener(OnSelectChangedListener onSelectChangedListener) {
        mOnSelectChangedListener = onSelectChangedListener;
    }

    public interface OnSelectChangedListener {
        void onSelectChanged(int p);
    }

    public FeedbackTypeAdapter(List<FeedbackType> feedbackTypes) {
        mFeedbackTypes = feedbackTypes;
    }

    @NonNull
    @Override
    public H onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new H(LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.layout_feedback_type, viewGroup, false)
        );
    }

    @Override
    public void onBindViewHolder(@NonNull H h, int i) {
        FeedbackType type = mFeedbackTypes.get(i);
        h.mCheckBox.setText(type.getModelName());

        h.mCheckBox.setChecked(selectPosition == i);

        h.mCheckBox.setTag(i);
        h.mCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int p = (int) v.getTag();
                if (p == selectPosition) {
                    p = -1;
                }
                selectPosition = p;
                notifyDataSetChanged();
                if (mOnSelectChangedListener != null) {
                    mOnSelectChangedListener.onSelectChanged(selectPosition);
                }
            }
        });
    }

    public int getSelectPosition() {
        return selectPosition;
    }

    public FeedbackType getSelected() {
        if (selectPosition > -1) {
            return mFeedbackTypes.get(selectPosition);
        }
        return null;
    }

    @Override
    public int getItemCount() {
        return mFeedbackTypes.size();
    }

    class H extends RecyclerView.ViewHolder {

        CheckBox mCheckBox;
        public H(@NonNull View itemView) {
            super(itemView);
            mCheckBox = itemView.findViewById(R.id.cb_type);
        }
    }
}
